package org.idea.spring.framework.event;

import org.springframework.context.*;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author linhao
 * @Date created in 10:14 下午 2021/5/29
 */
public class PayLoadEventDemo2 implements ApplicationEventPublisherAware {

    public ApplicationEventPublisher applicationEventPublisher;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(PayLoadEventDemo2.class);
        annotationConfigApplicationContext.register(MyPayloadApplicationEventListener.class);
        annotationConfigApplicationContext.refresh();
        PayLoadEventDemo2 payLoadEventDemo = annotationConfigApplicationContext.getBean(PayLoadEventDemo2.class);
        payLoadEventDemo.applicationEventPublisher.publishEvent("hello");
        payLoadEventDemo.applicationEventPublisher.publishEvent(new MyPayloadApplicationEvent<String>(payLoadEventDemo,"payload"));
        annotationConfigApplicationContext.close();
    }


    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 可以接收payload事件？
     */
    static class MyPayloadApplicationEventListener implements ApplicationListener<MyPayloadApplicationEvent>{

        @Override
        public void onApplicationEvent(MyPayloadApplicationEvent myPayloadApplicationEvent) {
            System.out.println("[MyPayloadApplicationEventListener] 接收到：%s,"+myPayloadApplicationEvent);
        }
    }

    static class MyPayloadApplicationEvent<String> extends PayloadApplicationEvent<String>  {

        /**
         * Create a new PayloadApplicationEvent.
         *
         * @param source  the object on which the event initially occurred (never {@code null})
         * @param payload the payload object (never {@code null})
         */
        public MyPayloadApplicationEvent(Object source, String payload) {
            super(source, payload);
        }
    }
}
